package com.woniuxy.redis.service.impl;

import com.woniuxy.redis.entity.Student;
import com.woniuxy.redis.service.StudentCacheService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: linKe
 * @Date: 2022/1/5 17:17
 * @FileName: StudentCacheServiceIMPL
 * @version: 1.0
 * @Description: 学生服务层的实现类
 * 使用RedisCache 进行缓存处理的实现类
 */
@Service
public class StudentCacheServiceImpl implements StudentCacheService {
    /**
     *   value:命名空间
     *   key: 键的名字，遵守SpringExpressionLanguage:  core    bean  context SPL
     *   SpringExpressionLanguage SpEL表达式
     * @param id 学生id
     * @return 结果
     */
    @Cacheable(value = "student",key ="#id" )
    @Override
    public Student getStudentById(int id) {
        System.out.println("数据库查询，存入缓存:"+id);
        Student student;
        if(id==1){
            student=new Student(1, "zs");
        }else {
            student=new Student(2,"ls");
        }
        return  student;
    }

    @Override
    @CachePut(value = "student",key = "#student.id")
    public Student addStudent(Student student) {
        System.out.println("执行数据库添加："+student);
        return student;
    }

    @Override
    @CachePut(value = "student",key = "#student.id")
    public Student modifyStudent(Student student) {
        System.out.println("执行数据库修改："+student);
        return student;
    }

    @Override
    @CacheEvict(value = "student",key = "#id")
    //@CacheEvict(value = "student",key = "#id",beforeInvocation = false)
    public void removeStudent(int id) {
        System.out.println("执行数据库删除："+id);
    }

}
